package cn.jesin.css.controller;

import cn.hutool.core.util.StrUtil;
import cn.jesin.css.common.Flag;
import cn.jesin.css.service.FileService;
import cn.jesin.css.vo.FileInfo;
import cn.jesin.css.vo.responseformat.Code;
import cn.jesin.css.vo.responseformat.Result;
import jakarta.annotation.Resource;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author 谷汉斌
 * @description
 * @createTime 2024/8/22 上午8:53
 */
@RestController
@CrossOrigin
@MultipartConfig(
        maxFileSize = 1024 * 1024 * 10,
        maxRequestSize = 1024 * 1024 * 10 * 5
)
public class FileController {


    @Resource
    private FileService fileService;

    /**
     * 上传文件
     *
     * @param file 文件
     * @return 上传成功返回结果
     */

    @PostMapping("/upload")
    public Result<FileInfo> upload(MultipartFile file) {
        if (file != null) {
            // 上传文件
            FileInfo fileInfo = fileService.upload(file);
            if (null != fileInfo) {
                return Result.<FileInfo>builder().code(Code.UPLOAD_SUCCESS.getCode()).flag(Flag.SUCCESS.isCode())
                        .message(Code.UPLOAD_SUCCESS.getInfo()).data(fileInfo).build();
            }
        }
        return Result.<FileInfo>builder().code(Code.UPLOAD_FAIL.getCode()).flag(Flag.FAIL.isCode())
                .message(Code.UPLOAD_FAIL.getInfo()).build();
    }


    /**
     * 下载文件
     *
     * @param fileName 要下载的文件的名称
     * @param response 响应对象
     */
    @GetMapping("/download/{fileName}")
    public Result<String> download(@PathVariable String fileName, HttpServletResponse response) {
        if (!StrUtil.isBlank(fileName)) {
            if (fileService.download(fileName, response)) {
                return Result.<String>builder().code(Code.DOWNLOAD_SUCCESS.getCode()).flag(Flag.SUCCESS.isCode())
                        .message(Code.DOWNLOAD_SUCCESS.getInfo()).build();
            }
        }
        return Result.<String>builder().code(Code.DOWNLOAD_FAIL.getCode()).flag(Flag.FAIL.isCode()).build();
    }


    /**
     * 删除文件
     *
     * @param fileName 要删除的文件的名称
     */
    @DeleteMapping("/delete-file/{fileName}")
    public void delete(@PathVariable String fileName) {
        fileService.delete(fileName);
    }
}
